<template>
    <div class="audio-box" ref="element" :style="`left: ${x}px;top: ${y}px;`">
        <div class="bg" :style="`background-image:url(${src})`"></div>
        <span class="icon"></span>
        <ul class="progress">
            <li :style="`width: ${w}px; float:left;`"></li>
        </ul>
        <audio controls autoplay @ended="addEndEvent" id="audio"
            :src="`https://music.163.com/song/media/outer/url?id=${musicid}.mp3`" ref="audio"></audio>
    </div>
</template>

<script>
export default {
    props: {
        // 子组件 用于记录父组件传递的参数
        rid: {
            type: [String, Number]
        },
        // 子组件 记录全部歌曲
        rsongList: {
            type: [Object, Array]
        }
    },
    data() {
        return {
            // 记录音频元素
            audio: null,
            // 记录进度条总宽度
            width: 60,
            // 计算音频播放的宽度
            w: 0,
            // 音频总时长
            duration: 0,
            // 音频当前播放时长
            cur: 0,
            // 记录音乐ID
            musicid: '',
            // 记录歌曲的索引值
            index: 0,
            src: '',
            // 记录手指滑动的数据
            startX: 0,
            startY: 0,
            curX: 0,
            curY: 0,
            moveX: 0,
            moveY: 0,
            x: 10,
            y: 550,

            // 控制用户轻触行为
            startTime:0,
            endTime: 0
        }
    },
    watch: {
        // rid(n,o){
        //     console.log("ID发生变化...")
        //     // 记录音乐ID
        //     this.musicid = n;
        //     this.init();
        // },
        // 监听音乐ID的变化
        rid: {
            immediate: true,
            handler(nid, oid) {
                // 根据ID设置当前播放的音乐
                this.musicid = nid;
                // 初始化audio元素(总时长/当前播放时长)
                this.init();
                // 计算索引值
                for (let i = 0; i < this.rsongList.length; i++) {
                    // 根据ID匹配歌曲的下标
                    if (this.rsongList[i].id == nid) {
                        this.index = i;
                        this.src = this.rsongList[i].picUrl;
                        break;
                    }
                }
            }
        }
    },
    mounted() {
        // 模板挂载完成... 操作DOM
        this.init();
        // 添加滑动行为
        this.addTouchEvent();
    },
    methods: {
        // 初始化歌曲信息
        init() {
            this.$nextTick(() => {
                if (this.$refs['audio']) {
                    this.audio = this.$refs['audio'];
                    // console.log('元素:',this.audio);
                    this.getAudioDuration();
                    this.getAudioCurrent();

                    // 测试
                    // this.audio.currentTime = 3.4 * 60
                }
            })
        },
        // 获取歌曲的总时长
        getAudioDuration() {
            this.audio.oncanplay = () => {
                // 获取音频文件总时长
                this.duration = this.audio.duration;
            }
        },
        // 获取歌曲的当前播放时长
        getAudioCurrent() {
            this.audio.ontimeupdate = () => {
                this.cur = this.audio.currentTime;
                this.w = (this.cur / this.duration) * this.width;
            }
        },
        // 监听音乐播放结束
        addEndEvent() {
            // 当前音频播放结束
            console.log("上一首歌曲播放结束")
            this.index++;
            if (this.index > this.rsongList.length - 1) {
                this.index = 0;
            }
            // 赋值给musicid
            this.musicid = this.rsongList[this.index].id;
            this.src = this.rsongList[this.index].picUrl;
            console.log("ID:", this.musicid);
            // 把当前这首歌的下标传值给父元素
            this.$emit('play-end', { index: this.index })
        },
        // 手指按下、滑动、松开音乐控件
        addTouchEvent() {
            this.$nextTick(() => {
                let ele = this.$refs['element'];
                let vx = parseFloat(getComputedStyle(ele)['left']);
                let vy = parseFloat(getComputedStyle(ele)['top']);
                this.curX = vx;
                this.curY = vy;
                this.x = vx;
                this.y = vy;
                // console.log({ vx, vy, ele });
                ele.ontouchstart = evt => {
                    this.startX = evt.touches[0].clientX;
                    this.startY = evt.touches[0].clientY;
                    // 滑动播放器时，禁止页面滚动
                    document.documentElement.style['height'] = '100%'
                    document.documentElement.style['overflow'] = 'hidden'
                    document.ontouchmove = event => {
                        let { clientX, clientY } = event.touches[0];
                        this.x = clientX - this.startX + this.curX;
                        this.y = clientY - this.startY + this.curY;
                    }
                    // 获取按下时的时间戳（从1970-01-01 00:00:00 到此时此分此秒此毫秒的这段时间） 毫秒
                    this.startTime = new Date().getTime();
                }
                document.ontouchend = () => {
                    this.curX = this.x;
                    this.curY = this.y;
                    document.ontouchmove = null;
                    document.documentElement.style['height'] = 'auto';
                    document.documentElement.style['overflow'] = 'auto';
                    // 获取松开手指时的时间戳
                    this.endTime = new Date().getTime();
                    // 判断时间是否小于 150 毫秒 （轻触 150ms）  | 点击 300ms click
                    if((this.endTime - this.startTime) < 150) {
                        // 跳转歌词页
                        this.$router.push({
                            path:'/lyric',
                            query: {id: this.musicid}
                        })
                    }
                    
                }
            })
        }
    },
    beforeRouteLeave (to, from, next) {
        this.$nextTick(() => {
            if (this.$refs['audio']) {
                this.$refs['audio'].pause();
                this.isPause = !this.isPause;
            }
        })
        next();
    },
    beforeDestroy(){
        this.musicid = '';
        this.$nextTick(() => {
            if (this.$refs['audio']) {
                this.$refs['audio'].pause();
                this.isPause = !this.isPause;
                this.audio = null;
            }
        })
    }
}

</script>

<style lang="scss">
@import '../static/style/variable.scss';

@keyframes rotate1 {
    0% {
        transform: rotateY(0deg);
    }

    100% {
        transform: rotateY(360deg);
    }
}


.audio-box {
    width: 2.1333rem;
    height: 2.1333rem;
    text-align: center;
    line-height: 2.1333rem;
    background-color: rgba(255, 255, 255, .8);
    border: 1px solid #f0f0f0;
    box-shadow: 0 2px 2px #ccc;
    border-radius: .2667rem;
    overflow: hidden;
    position: fixed;
    top: 14.6667rem;
    left: .2667rem;
    z-index: 1000;
    transform-style: preserve-3d;
    perspective: 21.3333rem;

    .bg {
        width: 100%;
        height: 100%;
        background-size: cover;
    }

    // 进度条
    .progress {
        width: 1.6rem;
        height: .1333rem;
        background-color: #f0f0f0;
        position: absolute;
        bottom: .0533rem;
        left: 50%;
        margin-left: -0.8rem;
        border-radius: .1333rem;

        li {
            height: .1333rem;
            width: 0px;
            background-color: $bgColor;
            border-radius: .1333rem;
            position: absolute;
            left: 0;
        }
    }


    .icon {
        display: inline-block;
        width: 1.3333rem;
        height: 1.3333rem;
        background-image: url(../static/images/i-music.png);
        background-size: cover;
        vertical-align: middle;
        // opacity: .5;
        position: absolute;
        left: 50%;
        top: 50%;
        margin-left: -0.6667rem;
        margin-top: -0.6667rem;
        animation: rotate1 5s linear infinite;
    }

    #audio {
        opacity: 0;
        width: 0;
        height: 0;
    }
}
</style>